#import "EditProfileViewController.h"
#import "CameraGalleryManager.h"
#import "PopUIManager.h"
#import "RequestServerAPI.h"
#import "JsonUtil.h"
#import "NetWorkManager.h"
#import "RelationShipViewController.h"
#import "Utils.h"

@interface EditProfileViewController ()
@property (weak, nonatomic) IBOutlet UIButton *userIcon;
@property (weak, nonatomic) IBOutlet UITextField *pwdInput;
@property (weak, nonatomic) IBOutlet UITextField *pwdConfirmInput;

@property (weak, nonatomic) IBOutlet UITextField *nicknameInput;

@property (weak, nonatomic) IBOutlet UITextField *inviteCodeInput;



@end

@implementation EditProfileViewController
@synthesize phoneNumber, avatarURL;
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    [self customView];
}
-(void)customView
{
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"填写家长资料";
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
    self.navigationItem.rightBarButtonItem
    =[[UIBarButtonItem alloc]initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(nextStep:)];
    
    [Utils textFiled:_pwdInput padding:15];
    [Utils textFiled:_pwdConfirmInput padding:15];
    [Utils textFiled:_nicknameInput padding:15];
    [Utils textFiled:_inviteCodeInput padding:15];
    self.view.backgroundColor = DefaultViewColor;
    
    NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:@"密码" attributes:@{ NSForegroundColorAttributeName : DefaultPlaceHolderColor }];
    self.pwdInput.attributedPlaceholder = str1;
    NSAttributedString *str2 = [[NSAttributedString alloc] initWithString:@"确认密码" attributes:@{ NSForegroundColorAttributeName : DefaultPlaceHolderColor }];
    self.pwdConfirmInput.attributedPlaceholder = str2;
    NSAttributedString *str3 = [[NSAttributedString alloc] initWithString:@"昵称" attributes:@{ NSForegroundColorAttributeName : DefaultPlaceHolderColor }];
    self.nicknameInput.attributedPlaceholder = str3;
    NSAttributedString *str4 = [[NSAttributedString alloc] initWithString:@"邀请码：(可选)" attributes:@{ NSForegroundColorAttributeName : DefaultPlaceHolderColor }];
    self.inviteCodeInput.attributedPlaceholder = str4;
    [self.view setBackgroundColor:DefaultViewColor];
}

- (IBAction)userIconCallback:(id)sender {
    
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选取照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册",nil];
    [sheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ((int)buttonIndex == 0) {  //拍照
        
        //延时0.3s调用相机
        [self performSelector:@selector(showCamera) withObject:nil afterDelay:0.3];
    }else if ((int)buttonIndex == 1){//相册
        
        [[CameraGalleryManager getInstanse] gallerySelect:self finishBlock:^(UIImage *img, NSString * avaURL) {
            
            [self.userIcon setImage:img forState:UIControlStateNormal];
            avatarURL = avaURL;
        }];
    }else if ((int)buttonIndex == 2){//取消
        debugLog(@"取消");
    }
}

-(void) showCamera{
    [[CameraGalleryManager getInstanse] takePhoto:self finishBlock:^(UIImage *img, NSString * avaURL) {
       
        [self.userIcon setImage:img forState:UIControlStateNormal];
        avatarURL = avaURL;
    }];
}

- (void)nextStep:(id)sender {
    NSString *pwd = self.pwdInput.text;
    NSString *pwdConfirm = self.pwdConfirmInput.text;
    NSString *name = _nicknameInput.text;
    NSString *code = _inviteCodeInput.text;
    
    if (pwd.length == 0 || pwdConfirm.length == 0) {
        [[PopUIManager getInstanse]popAlertView:self title:@"提示" message:@"密码不允许为空" cancelButtonTitle:@"确定"];
        return;
    }
    
    if(pwd.length<6){
        [[PopUIManager getInstanse] popAlertView:self title:@"提示" message:@"密码至少6位" cancelButtonTitle:@"确定"];
        return;
    }
    
    if (![pwd isEqualToString:pwdConfirm]) {
        [[PopUIManager getInstanse]popAlertView:self title:@"提示" message:@"两次输入的密码不一致" cancelButtonTitle:@"确定"];
        return;
    }
    
    if ([name isEqualToString:@""]) {
        [[PopUIManager getInstanse]popAlertView:self title:@"提示" message:@"昵称不允许为空" cancelButtonTitle:@"确定"];
        return;
    }
    if(![code isEqualToString:@""] &&code.length>0){
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:code, @"invite_code", nil];
        
        NSString *dataString = [JsonUtil convertDictionaryToJson:dict];
        
        PopUIManager *popUIMgr = [PopUIManager getInstanse];
        [popUIMgr showWaitingUI:self.view];
        
        [[NetWorkManager getInstanse] requestURLAsynMessage:PARENT_CHECK_INVITE_CODE data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            [popUIMgr removeWaitingUI];
            if (connectionError) { //连接失败
                debugLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
                NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
                [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
            }else{//连接成功，判断是否有数据返回
                
                if (data) {
                    NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                    NSLog(@"数据字典: %@", dict);
                    
                    if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                        //登录失败，弹窗提示
                        NSString *ret_msg;
                        switch ([[dict objectForKey:@"retCode"] integerValue]) {
                            case 1:
                               {
                                   ret_msg= @"Success";
                                   break;
                                }
                            case 2:{
                                ret_msg= @"邀请码不存在";
                                break;
                            }
                        }
                        if (![ret_msg isEqual:@"Success"]) {
                            [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                            return;
                        }
                    }else{
                        [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                        return;
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
                    return;
                }
            }
            
        }];
    }
    RelationShipViewController *relationship = [[RelationShipViewController alloc]init];
    relationship.nickname = name;
    relationship.inviteCode = code;
    relationship.password =pwd;
    relationship.avatar = avatarURL;
    relationship.phoneNum = phoneNumber;
    [self.navigationController pushViewController:relationship animated:YES];
   // [RequestServerAPI apiTeacherRegister:self userName:name password:pwd phoneNumber:phoneNumber avatar:avatarURL];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
